package com.csu.backmanagesys.Controller;

import com.csu.backmanagesys.Domain.Account;
import com.csu.backmanagesys.Domain.Item;
import com.csu.backmanagesys.Domain.Product;
import com.csu.backmanagesys.Mapper.ItemMapper;
import com.csu.backmanagesys.Service.*;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.math.BigDecimal;
//import java.net.http.HttpRequest;
import java.sql.Timestamp;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {
    @GetMapping("/aboutUs")
    public ModelAndView login()throws Exception{
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("aboutUs");
        return modelAndView;
    }

    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest req)throws Exception{
        HttpSession session = req.getSession();
        ModelAndView modelAndView = new ModelAndView();
        if(session.getAttribute("admin") == null){
            modelAndView.setViewName("signOn");
        }else {
            modelAndView.setViewName("index");
        }
        return modelAndView;
    }

    @RequestMapping("/product_manager")
    public ModelAndView products()throws Exception{
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("product_manager");
        return modelAndView;
    }
    @GetMapping("/product_manager")
    @ResponseBody
    public ModelAndView product()throws Exception{
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("product",productService.selectProduct());
        modelAndView.setViewName("product_manager");
        return modelAndView;
    }

    @Autowired
    public ItemService itemService;
    @RequestMapping("/item_manager")
    public ModelAndView items()throws Exception{
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("item",itemService.selectItem());
        modelAndView.setViewName("item_manager");
        return modelAndView;
    }

    @GetMapping("/selectItem")
    public ModelAndView selectItem(ModelAndView modelAndView,String search)throws Exception{
        modelAndView.addObject("item",itemService.fuzzySelectItem(search));
        modelAndView.setViewName("item_manager");
        return modelAndView;
    }

    @GetMapping("/selectProduct")
    public ModelAndView selectProduct(ModelAndView modelAndView,String search)throws Exception{
        modelAndView.addObject("product",productService.fuzzySelectProduct(search));
        modelAndView.setViewName("product_manager");
        return modelAndView;
    }


    @GetMapping("/item_manager/delete/{itemId}")
    public ModelAndView deleteItem(ModelAndView modelAndView,@PathVariable String itemId){
//        System.out.println(itemId);
        itemService.deleteItem(itemId);
        modelAndView.addObject("item",itemService.selectItem());
        modelAndView.setViewName("item_manager");
        return modelAndView;
    }

    @PostMapping("/addNewItem")
    public ModelAndView addNewItem(HttpServletRequest httpServletRequest,ModelAndView modelAndView){
        String listprice = httpServletRequest.getParameter("listprice");
        String unitprice = httpServletRequest.getParameter("unitprice");
        if(listprice!=null&unitprice!=null){
            BigDecimal list_price = new BigDecimal(0);
            BigDecimal unit_price = new BigDecimal(0);
           list_price = new BigDecimal(listprice);
           unit_price = new BigDecimal(unitprice);
           itemService.insertItem(
                   httpServletRequest.getParameter("itemid"),
                   httpServletRequest.getParameter("productid"),
                   list_price,
                   unit_price,
                   1,
                   "P",
                   httpServletRequest.getParameter("attr1"),
                   httpServletRequest.getParameter("attr2"),
                   httpServletRequest.getParameter("attr3"),
                   httpServletRequest.getParameter("attr4"),
                   httpServletRequest.getParameter("attr5")
           );
           itemService.insertInventory(
                   httpServletRequest.getParameter("itemid"),
                   Integer.parseInt(httpServletRequest.getParameter("qty"))

           );
       }
        modelAndView.addObject("item",itemService.selectItem());
        modelAndView.setViewName("item_manager");
        return modelAndView;
    }
    @PostMapping("/addNewProduct")
    public ModelAndView addNewProduct(HttpServletRequest httpServletRequest,ModelAndView modelAndView){
        productService.insertProduct(
                httpServletRequest.getParameter("productId2"),
                httpServletRequest.getParameter("category2"),
                httpServletRequest.getParameter("name2"),
                httpServletRequest.getParameter("description2")
        );
        System.out.print(  httpServletRequest.getParameter("productId2"));
        modelAndView.addObject("product",productService.selectProduct());
        modelAndView.setViewName("item_manager");
        return modelAndView;
    }
//    @Autowired
//    public AccountService AccountService;
//
//    @Autowired
//    public IdAndPasswordService idAndPasswordService;
//
//    @GetMapping("/user")
//    public ModelAndView user(){
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.addObject("Account",AccountService.selectAccountId());
//        modelAndView.setViewName("userInformation1");
//        return modelAndView;
//    }
//
//    @GetMapping("user/reset_user_password")
//    public ModelAndView reset_user_password(String userid){
//        ModelAndView modelAndView = new ModelAndView();
//        idAndPasswordService.updateIdAndPassword(userid , "123456");
//        modelAndView.addObject("Account",AccountService.selectAccountId());
//        modelAndView.setViewName("userInformation1");
//        return modelAndView;
//    }
//
//    @PostMapping ("update_user_information")
//    public ModelAndView update_user_information(HttpServletRequest httpRequest){
//        ModelAndView modelAndView = new ModelAndView();
//        Account account = new Account();
//        account.setUserid(httpRequest.getParameter("userid"));
//        account.setEmail(httpRequest.getParameter("email"));
//        account.setFirstName(httpRequest.getParameter("firstname"));
//        account.setLastName(httpRequest.getParameter("lastname"));
//        account.setStatus(httpRequest.getParameter("status"));
//        account.setAddress1(httpRequest.getParameter("addr1"));
//        account.setAddress2(httpRequest.getParameter("addr2"));
//        account.setCity(httpRequest.getParameter("city"));
//        account.setState(httpRequest.getParameter("state"));
//        account.setZip(httpRequest.getParameter("zip"));
//        account.setCountry(httpRequest.getParameter("country"));
//        account.setPhone(httpRequest.getParameter("phone"));
//        System.out.println(account.toString());
//        AccountService.updateAccount_information(account);
//        modelAndView.addObject("Account",AccountService.selectAccountId());
//        modelAndView.setViewName("userInformation1");
//        return modelAndView;
//    }
//
//    //搜索
//    @GetMapping("/selectUserInf")
//    public ModelAndView selectUserInf(String search){
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.addObject("Account",AccountService.selectAccountById(search));
//        modelAndView.setViewName("userInformation1");
//        return modelAndView;
//    }
//    //寻找
//    @GetMapping("/getUserInf")
//    @ResponseBody
//    public List<Account> getUserInf(HttpServletRequest req){
////        modelAndView.addObject("oneAccount",AccountService.selectAccountById(userId));
////        modelAndView.setViewName("");
////        return modelAndView;
//        String userId = req.getParameter("userId");
//        return AccountService.selectAccountById(userId);
//    }

    @Autowired
    public OrderService OrderService;
    @GetMapping("/order_manager")
    public ModelAndView order(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("order",OrderService.selectOrder());
        modelAndView.setViewName("order_manager");
        return modelAndView;
    }

    @GetMapping("/selectOrder")
    public ModelAndView selectOrder(ModelAndView modelAndView,String search){
        modelAndView.addObject("order",OrderService.fuzzySelectOrder(search));
        modelAndView.setViewName("order_manager");
        return modelAndView;
    }

    @GetMapping("/order_manager/delete/{orderId}")
    public ModelAndView deleteOrder(ModelAndView modelAndView,@PathVariable String orderId){
        System.out.println(orderId);
        OrderService.deleteOrder(orderId);
        modelAndView.addObject("order",OrderService.selectOrder());
        modelAndView.setViewName("order_manager");
        return modelAndView;
    }

    @GetMapping("/order_manager/all")
    public ModelAndView selectOrderAll(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("order",OrderService.selectOrder());
        modelAndView.setViewName("order_manager");
        return modelAndView;
    }

    @GetMapping("/order_manager/done")
    public ModelAndView selectOrderDone(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("order",OrderService.selectOrderStatus("P"));
        modelAndView.setViewName("order_manager");
        return modelAndView;
    }

    @GetMapping("/order_manager/undone")
    public ModelAndView selectOrderUnDone(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("order",OrderService.selectOrderStatus("S"));
        modelAndView.setViewName("order_manager");
        return modelAndView;
    }


    //改item信息先用这个
    @PostMapping("/update_item_information")
    public ModelAndView updateItem(HttpServletRequest req){

        String itemid = req.getParameter("itemid_edit");
        System.out.println("/update_item_information itemid=" + itemid);
        String productid = req.getParameter("productid_edit");
        BigDecimal listprice = new BigDecimal(req.getParameter("listprice_edit"));
        BigDecimal unitcost = new BigDecimal(req.getParameter("unitcost_edit"));
        String attr1 = req.getParameter("attr1_edit");
        String attr2 = req.getParameter("attr2_edit");
        String attr3 = req.getParameter("attr3_edit");
        String attr4 = req.getParameter("attr4_edit");
        String attr5 = req.getParameter("attr5_edit");

        itemService.updateItem(itemid,productid,listprice,unitcost,1,"p",attr1,attr2,attr3,attr4,attr5);
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("item",itemService.selectItem());
        modelAndView.setViewName("item_manager");
        return modelAndView;

    }

    @GetMapping("/getItemInf")
    @ResponseBody
    public List<Item> getItemInf(HttpServletRequest req){
        String itemId = req.getParameter("itemid_edit");
        System.out.println("/getItemInf itemid_edit=" + itemId);
        return itemService.selectItemById(itemId);
    }



    @PostMapping("/update_product_information")
    public ModelAndView updateProduct(HttpServletRequest req){
        String productId = req.getParameter("productId");
        String categoryId = req.getParameter("categoryId");
        String name = req.getParameter("name");
        String descn = req.getParameter("description");
        if(productId.length()!=0 && categoryId.length()!= 0){
            productService.updateProduct(productId,categoryId,name,descn);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("product",productService.selectProduct());
        modelAndView.setViewName("product_manager");
        return modelAndView;
    }

    @PostMapping("/update_product_information_name")
    public ModelAndView updateProductName(HttpServletRequest req){


       String productId = req.getParameter("productId");
//        String categoryId = req.getParameter("categoryId");
        String name = req.getParameter("name");
        //String descn = req.getParameter("description");


        productService.updateProductName(name,productId );
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("product",productService.selectProduct());
        modelAndView.setViewName("product_manager");
        return modelAndView;
    }
    @PostMapping("/update_product_information_description")
    public ModelAndView updateProductDescription(HttpServletRequest req){


        String productId = req.getParameter("productId");
//        String categoryId = req.getParameter("categoryId");
        String description= req.getParameter("description");
        //String descn = req.getParameter("description");


        productService.updatePicture(productId,description );
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("product",productService.selectProduct());
        modelAndView.setViewName("product_manager");
        return modelAndView;
    }

    @Autowired
    public ProductService productService;
    @GetMapping("/getProductInf")
    @ResponseBody
    public List<Product> getProductInf(HttpServletRequest req)
    {
        String productId = req.getParameter("productId");
        System.out.println("testtttttt"+productId);
        return productService.selectProductById(productId);
    }

    @PostMapping("/upload")
    public ModelAndView handleFileUpload(MultipartFile image,@RequestHeader("product") String product) throws IOException {
        // 对上传的文件进行处理 @RequestHeader("product") String product
        ModelAndView modelAndView = new ModelAndView();
        try {
            modelAndView.setViewName("product_manager");
            byte[] fileBytes = image.getBytes();
            String head_inf = "data:image/png;base64,";
            String encodedFile = Base64.getEncoder().encodeToString(fileBytes);
            String result = head_inf + encodedFile;
            System.out.println("这个productId" + product);
            productService.updatePicture(product,result);
            modelAndView.addObject("product",productService.selectProduct());
            return modelAndView;
        } catch (IOException e) {
            System.out.println("文件转码失败");
            modelAndView.setViewName("product_manager");
            modelAndView.addObject("product",productService.selectProduct());
            return modelAndView;
        }
    }

    @DeleteMapping("/deleteProduct")
    @ResponseBody
    public String deleteProduct(@RequestParam("product") String productId) {
        productService.deleteProduct(productId);
        return "delete product!";
    }
}
